using System;
using System.Runtime.Serialization;
using BanZuiCloudControlAgent.Utils.Logging;
using Newtonsoft.Json;

namespace BanZuiCloudControlAgent.Utils.Common
{
    /// <summary>
    /// JSON序列化助手类，统一处理JSON序列化/反序列化操作
    /// </summary>
    public static class JsonHelper
    {
        private static readonly Logger _logger = LogManager.GetLogger(nameof(JsonHelper));

        /// <summary>
        /// 将对象序列化为JSON字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="indented">是否使用缩进格式</param>
        /// <returns>JSON字符串</returns>
        public static string Serialize<T>(T obj, bool indented = false)
        {
            try
            {
                return JsonConvert.SerializeObject(obj, indented ? Formatting.Indented : Formatting.None);
            }
            catch (Exception ex)
            {
                string typeName = typeof(T).Name;
                _logger.Error($"序列化对象失败: {typeName}", ex);
                throw new JsonSerializationException(
                    $"序列化对象失败: {typeName}",
                    typeName,
                    "Serialize",
                    ex
                );
            }
        }

        /// <summary>
        /// 将JSON字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T Deserialize<T>(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                _logger.Warn($"反序列化JSON失败: 输入为空, 目标类型: {typeof(T).Name}");
                return default;
            }

            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                string typeName = typeof(T).Name;
                _logger.Error($"反序列化JSON失败: {typeName}", ex);
                throw new JsonSerializationException(
                    $"反序列化JSON失败: {typeName}",
                    typeName,
                    "Deserialize",
                    ex
                );
            }
        }

        /// <summary>
        /// 将JSON字符串反序列化为指定类型的对象
        /// </summary>
        /// <param name="json">JSON字符串</param>
        /// <param name="type">目标对象类型</param>
        /// <returns>反序列化后的对象</returns>
        public static object Deserialize(string json, Type type)
        {
            if (string.IsNullOrEmpty(json))
            {
                _logger.Warn($"反序列化JSON失败: 输入为空, 目标类型: {type.Name}");
                return null;
            }

            try
            {
                return JsonConvert.DeserializeObject(json, type);
            }
            catch (Exception ex)
            {
                string typeName = type.Name;
                _logger.Error($"反序列化JSON失败: {typeName}", ex);
                throw new JsonSerializationException(
                    $"反序列化JSON失败: {typeName}",
                    typeName,
                    "Deserialize",
                    ex
                );
            }
        }

        /// <summary>
        /// 尝试将JSON字符串反序列化为对象，失败时返回默认值而不抛出异常
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>反序列化后的对象，失败时返回默认值</returns>
        public static T TryDeserialize<T>(string json, T defaultValue = default)
        {
            if (string.IsNullOrEmpty(json))
            {
                _logger.Debug($"尝试反序列化空JSON: {typeof(T).Name}, 返回默认值");
                return defaultValue;
            }

            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                _logger.Warn($"尝试反序列化JSON失败: {typeof(T).Name}, 返回默认值", ex);
                return defaultValue;
            }
        }

        /// <summary>
        /// 将对象转换为另一个类型的对象（通过JSON序列化和反序列化）
        /// </summary>
        /// <typeparam name="TSource">源对象类型</typeparam>
        /// <typeparam name="TTarget">目标对象类型</typeparam>
        /// <param name="source">源对象</param>
        /// <returns>转换后的对象</returns>
        public static TTarget Convert<TSource, TTarget>(TSource source)
        {
            if (source == null)
            {
                return default;
            }

            try
            {
                string json = Serialize(source);
                return Deserialize<TTarget>(json);
            }
            catch (Exception ex)
            {
                string sourceType = typeof(TSource).Name;
                string targetType = typeof(TTarget).Name;
                _logger.Error($"对象转换失败: {sourceType} -> {targetType}", ex);
                throw new JsonSerializationException(
                    $"对象转换失败: {sourceType} -> {targetType}",
                    $"{sourceType}->{targetType}",
                    "Convert",
                    ex
                );
            }
        }

        /// <summary>
        /// 检查字符串是否为有效的JSON格式
        /// </summary>
        /// <param name="json">要检查的JSON字符串</param>
        /// <returns>是否为有效的JSON</returns>
        public static bool IsValidJson(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return false;
            }

            try
            {
                JsonConvert.DeserializeObject(json);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
} 